{% extends 'base.html' %}

{% block title %}{% if asset %}编辑资产{% else %}新增资产{% endif %} - 固定资产管理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-8">
        <h2 class="d-flex align-items-center gap-3">
            {% if asset %}编辑资产{% else %}新增资产{% endif %}
            <small class="text-muted">|</small>
            <span class="badge bg-info text-dark" id="org-badge" title="当前所属组织">
                {% if asset and asset.ledger and asset.ledger.organization %}
                    {{ asset.ledger.organization.name }}
                {% elif organization_id and organizations %}
                    {% for org in organizations %}{% if org.id == organization_id %}{{ org.name }}{% endif %}{% endfor %}
                {% else %}
                    未选择组织
                {% endif %}
            </span>
        </h2>
        
        <form method="post" enctype="multipart/form-data">
            {% csrf_token %}
            
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="name" class="form-label">资产名称 *</label>
                        <input type="text" class="form-control" id="name" name="name" value="{% if asset %}{{ asset.name }}{% else %}{{ name|default:'' }}{% endif %}" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="asset_number" class="form-label">资产编号 *</label>
                        <input type="text" class="form-control" id="asset_number" name="asset_number" value="{% if asset %}{{ asset.asset_number }}{% else %}{{ asset_number|default:'' }}{% endif %}" required>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="category" class="form-label">资产类别 *</label>
                        <select class="form-select" id="category" name="category" required>
                            <option value="">请选择资产类别</option>
                            {% for category in categories %}
                                <option value="{{ category.id }}" {% if asset and asset.category_id == category.id or category_id|add:"0" == category.id %}selected{% endif %}>
                                    {{ category.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="status" class="form-label">资产状态 *</label>
                        <select class="form-select" id="status" name="status" required>
                            <option value="idle" {% if asset and asset.status == 'idle' or status == 'idle' %}selected{% endif %}>闲置</option>
                            <option value="in_use" {% if asset and asset.status == 'in_use' or status == 'in_use' %}selected{% endif %}>在用</option>
                            <option value="borrowed" {% if asset and asset.status == 'borrowed' or status == 'borrowed' %}selected{% endif %}>已借出</option>
                            <option value="maintenance" {% if asset and asset.status == 'maintenance' or status == 'maintenance' %}selected{% endif %}>维修中</option>
                            <option value="faulty" {% if asset and asset.status == 'faulty' or status == 'faulty' %}selected{% endif %}>故障</option>
                            <option value="scrapped" {% if asset and asset.status == 'scrapped' or status == 'scrapped' %}selected{% endif %}>已报废</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="organization" class="form-label">所属组织（账簿归属）</label>
                        <select class="form-select" id="organization" name="organization">
                            <option value="">请选择组织</option>
                            {% if organizations %}
                                {% for org in organizations %}
                                    <option value="{{ org.id }}"
                                        {% if asset and asset.ledger and asset.ledger.organization_id == org.id %}selected{% elif organization_id|add:"0" == org.id %}selected{% endif %}>
                                        {{ org.name }}
                                    </option>
                                {% endfor %}
                            {% endif %}
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="ledger" class="form-label">账簿</label>
                        <select class="form-select" id="ledger" name="ledger">
                            <option value="">请选择账簿</option>
                            {% if ledgers %}
                                {% for ledger in ledgers %}
                                    <option value="{{ ledger.id }}" data-org="{{ ledger.organization.id }}" data-org-name="{{ ledger.organization.name }}"
                                        {% if asset and asset.ledger_id == ledger.id %}selected{% elif ledger_id|add:"0" == ledger.id %}selected{% endif %}>
                                        {% if not organization_id %}
                                            {% if not asset or not asset.ledger or not asset.ledger.organization_id %}
                                                {{ ledger.organization.name }} /
                                            {% endif %}
                                        {% endif %}
                                        {{ ledger.name }}
                                    </option>
                                {% endfor %}
                            {% endif %}
                        </select>
                        <div class="form-text">可先选择“所属组织”以便仅显示该组织下的账簿。</div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="department" class="form-label">所属部门</label>
                        <select class="form-select" id="department" name="department">
                            <option value="">请选择部门</option>
                            {% for department in departments %}
                                <option value="{{ department.id }}" {% if asset and asset.department_id == department.id or department_id|add:"0" == department.id %}selected{% endif %}>
                                    {{ department.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="location" class="form-label">位置</label>
                        <select class="form-select" id="location" name="location">
                            <option value="">请选择位置</option>
                            {% for location in locations %}
                                <option value="{{ location.id }}" {% if asset and asset.location_id == location.id or location_id|add:"0" == location.id %}selected{% endif %}>
                                    {{ location.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="user" class="form-label">使用人</label>
                        <select class="form-select" id="user" name="user">
                            <option value="">请选择使用人</option>
                            {% for user in users %}
                                <option value="{{ user.id }}" {% if asset and asset.user_id == user.id or user_id|add:"0" == user.id %}selected{% endif %}>
                                    {{ user.username }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="supplier" class="form-label">供应商</label>
                        <select class="form-select" id="supplier" name="supplier">
                            <option value="">请选择供应商</option>
                            {% for supplier in suppliers %}
                                <option value="{{ supplier.id }}" {% if asset and asset.supplier_id == supplier.id or supplier_id|add:"0" == supplier.id %}selected{% endif %}>
                                    {{ supplier.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="contract" class="form-label">合同</label>
                        <select class="form-select" id="contract" name="contract">
                            <option value="">请选择合同</option>
                            {% for contract in contracts %}
                                <option value="{{ contract.id }}" {% if asset and asset.contract_id == contract.id or contract_id|add:"0" == contract.id %}selected{% endif %}>
                                    {{ contract.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="purchase_date" class="form-label">启用日期 *</label>
                        <input type="date" class="form-control" id="purchase_date" name="purchase_date" value="{% if asset %}{{ asset.purchase_date|date:'Y-m-d' }}{% else %}{{ purchase_date|default:'' }}{% endif %}" required>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="purchase_price" class="form-label">采购价格 *</label>
                        <input type="number" class="form-control" id="purchase_price" name="purchase_price" step="0.01" value="{% if asset %}{{ asset.purchase_price }}{% else %}{{ purchase_price|default:'' }}{% endif %}" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="warranty_period" class="form-label">保修期(月)</label>
                        <input type="number" class="form-control" id="warranty_period" name="warranty_period" value="{% if asset %}{{ asset.warranty_period }}{% else %}{{ warranty_period|default:'' }}{% endif %}">
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="depreciation_rate" class="form-label">折旧率(%)</label>
                        <input type="number" class="form-control" id="depreciation_rate" name="depreciation_rate" step="0.01" value="{% if asset %}{{ asset.depreciation_rate }}{% else %}{{ depreciation_rate|default:'' }}{% endif %}">
                    </div>
                </div>
            </div>
            
            <div class="mb-3">
                <label for="description" class="form-label">描述</label>
                <textarea class="form-control" id="description" name="description" rows="3">{% if asset %}{{ asset.description }}{% else %}{{ description|default:'' }}{% endif %}</textarea>
            </div>
            
            <!-- 资产图片上传 -->
            <div class="mb-3">
                <label for="image" class="form-label">资产图片</label>
                {% if asset and asset.get_primary_image_url %}
                    <div class="mb-2">
                        <img src="{{ asset.get_primary_image_url }}" alt="{{ asset.name }}" 
                             style="max-width: 200px; max-height: 200px; object-fit: cover; border-radius: 8px; border: 1px solid #dee2e6;">
                        <div class="mt-1">
                            <small class="text-muted">当前图片</small>
                        </div>
                    </div>
                {% endif %}
                <input type="file" class="form-control" id="image" name="image" accept="image/*">
                <div class="form-text">支持 JPG、PNG、GIF 格式，建议尺寸不超过 2MB</div>
            </div>
            
            <!-- 额外图片上传 -->
            <div class="mb-3">
                <label class="form-label">额外图片 
                    {% if asset %}
                        <small class="text-muted">(当前: {{ asset.get_image_count }}/10)</small>
                    {% else %}
                        <small class="text-muted">(最多10张)</small>
                    {% endif %}
                </label>
                <div id="additional-images">
                    {% if asset %}
                        {% for img in asset.asset_images.all %}
                            <div class="d-flex align-items-center mb-2 existing-image" data-image-id="{{ img.id }}">
                                <img src="{{ img.get_image_url }}" alt="{{ img.title }}" 
                                     style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px; margin-right: 10px;">
                                <div class="flex-grow-1">
                                    <input type="text" class="form-control form-control-sm mb-1" 
                                           name="existing_image_title_{{ img.id }}" 
                                           value="{{ img.title }}" placeholder="图片标题">
                                    <textarea class="form-control form-control-sm" 
                                              name="existing_image_description_{{ img.id }}" 
                                              rows="2" placeholder="图片描述">{{ img.description }}</textarea>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-danger ms-2" 
                                        onclick="removeExistingImage('{{ img.id }}')">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </div>
                        {% endfor %}
                    {% endif %}
                </div>
                {% if not asset or asset.can_add_more_images %}
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addImageUpload()">
                        <i class="fa fa-plus"></i> 添加图片
                    </button>
                {% else %}
                    <small class="text-muted">已达到图片上限</small>
                {% endif %}
            </div>
            
            <div class="mb-3">
                <button type="submit" class="btn btn-primary">{% if asset %}更新{% else %}创建{% endif %}</button>
                <a href="{% url 'assets:asset_list' %}" class="btn btn-secondary">取消</a>
            </div>
        </form>
    </div>
</div>

<script>
let imageUploadCounter = 0;
const maxImages = 10;

function addImageUpload() {
    // 检查图片数量限制
    const existingImages = document.querySelectorAll('.existing-image').length;
    const newImages = document.querySelectorAll('.new-image-upload').length;
    const mainImage = document.querySelector('input[name="image"]').files.length;
    
    if (existingImages + newImages + mainImage >= maxImages) {
        alert(`最多只能上传${maxImages}张图片`);
        return;
    }
    
    imageUploadCounter++;
    const container = document.getElementById('additional-images');
    const imageUploadDiv = document.createElement('div');
    imageUploadDiv.className = 'd-flex align-items-start mb-2 new-image-upload';
    imageUploadDiv.innerHTML = `
        <div class="flex-grow-1">
            <input type="file" class="form-control form-control-sm mb-1" 
                   name="additional_images_${imageUploadCounter}" accept="image/*" 
                   onchange="validateImageFile(this)">
            <input type="text" class="form-control form-control-sm mb-1" 
                   name="additional_image_title_${imageUploadCounter}" placeholder="图片标题">
            <textarea class="form-control form-control-sm" 
                      name="additional_image_description_${imageUploadCounter}" 
                      rows="2" placeholder="图片描述"></textarea>
        </div>
        <button type="button" class="btn btn-sm btn-outline-danger ms-2" 
                onclick="removeImageUpload(this)">
            <i class="fa fa-trash"></i>
        </button>
    `;
    container.appendChild(imageUploadDiv);
}

function validateImageFile(input) {
    const file = input.files[0];
    if (file) {
        // 检查文件大小（2MB限制）
        if (file.size > 2 * 1024 * 1024) {
            alert('图片文件大小不能超过2MB');
            input.value = '';
            return;
        }
        
        // 检查文件类型
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        if (!allowedTypes.includes(file.type)) {
            alert('只支持 JPG、PNG、GIF 格式的图片');
            input.value = '';
            return;
        }
    }
}

function removeImageUpload(button) {
    button.closest('.new-image-upload').remove();
}

function removeExistingImage(imageId) {
    if (confirm('确定要删除这张图片吗？')) {
        const imageDiv = document.querySelector(`[data-image-id="${imageId}"]`);
        imageDiv.style.display = 'none';
        
        // 添加隐藏字段标记要删除的图片
        const hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = 'delete_images';
        hiddenInput.value = imageId;
        document.querySelector('form').appendChild(hiddenInput);
    }
}

// 图片预览功能
document.getElementById('image').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        // 验证文件
        if (!validateImageFile(this)) {
            return;
        }
        
        const reader = new FileReader();
        reader.onload = function(e) {
            // 移除现有预览
            const existingPreview = document.getElementById('image-preview');
            if (existingPreview) {
                existingPreview.remove();
            }
            
            // 创建新预览
            const preview = document.createElement('div');
            preview.id = 'image-preview';
            preview.className = 'mt-2';
            preview.innerHTML = `
                <img src="${e.target.result}" alt="预览" 
                     style="max-width: 200px; max-height: 200px; object-fit: cover; border-radius: 8px; border: 1px solid #dee2e6;">
                <div class="mt-1">
                    <small class="text-muted">新图片预览 (${(file.size / (1024 * 1024)).toFixed(2)}MB)</small>
                </div>
            `;
            document.getElementById('image').parentNode.appendChild(preview);
        };
        reader.readAsDataURL(file);
    }
});

// 根据组织筛选账簿下拉选项（前端筛选，无需请求后端）
document.addEventListener('DOMContentLoaded', function() {
    const orgSelect = document.getElementById('organization');
    const ledgerSelect = document.getElementById('ledger');
    const orgBadge = document.getElementById('org-badge');
    if (!orgSelect || !ledgerSelect) return;

    // 缓存所有账簿选项
    const allLedgerOptions = Array.from(ledgerSelect.querySelectorAll('option'))
        .filter(opt => opt.value !== '');

    const placeholder = ledgerSelect.querySelector('option[value=""]');

    function rebuildLedgerOptions(orgId) {
        // 保留占位
        ledgerSelect.innerHTML = '';
        if (placeholder) {
            ledgerSelect.appendChild(placeholder.cloneNode(true));
        }
        const fragment = document.createDocumentFragment();
        const toShow = !orgId ? allLedgerOptions
                               : allLedgerOptions.filter(opt => String(opt.getAttribute('data-org')) === String(orgId));
        toShow.forEach(opt => fragment.appendChild(opt.cloneNode(true)));
        ledgerSelect.appendChild(fragment);
        // 若当前选中的账簿不在新列表中，则重置为空
        const current = ledgerSelect.value;
        if (!current || !Array.from(ledgerSelect.options).some(o => o.value === current)) {
            ledgerSelect.value = '';
        }
    }

    // 初始化
    function updateOrgBadge() {
        const orgId = orgSelect.value;
        if (orgId) {
            const selected = orgSelect.options[orgSelect.selectedIndex];
            orgBadge.textContent = selected ? selected.textContent.trim() : '未选择组织';
            return;
        }
        const ledgerOpt = ledgerSelect.options[ledgerSelect.selectedIndex];
        const fromLedgerName = ledgerOpt ? ledgerOpt.getAttribute('data-org-name') : '';
        orgBadge.textContent = fromLedgerName ? fromLedgerName : '未选择组织';
    }

    rebuildLedgerOptions(orgSelect.value);
    updateOrgBadge();
    orgSelect.addEventListener('change', function(e) {
        rebuildLedgerOptions(e.target.value);
        updateOrgBadge();
    });
    ledgerSelect.addEventListener('change', function() {
        // 若未明确选择组织，则随所选账簿显示组织名称
        if (!orgSelect.value) {
            updateOrgBadge();
        }
    });
});
</script>

{% endblock %}